package com.google.p2pbench;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class LogListAdapter extends BaseAdapter {
  private final LayoutInflater mLayoutInflater;
  private final DateFormat mDateFormat;
  private final ArrayList<LogMessage> mLogMessages = new ArrayList<LogMessage>();
  
  private static class LogMessage {
    Date date;
    String tag;
    String message;

    LogMessage(Date d, String t, String m) {
      date = d;
      tag = t;
      message = m;
    }
  }

  private static class LogMessageHolder {
    @SuppressWarnings("unused")
    View view;
    TextView textDate;
    TextView textContent;

    LogMessageHolder(View v, TextView td, TextView tc) {
      view = v;
      textDate = td;
      textContent = tc;
    }
  }

  public LogListAdapter(LayoutInflater inflater) {
    mLayoutInflater = inflater;
    // mDateFormat = android.text.format.DateFormat.getTimeFormat(this);
    mDateFormat = new SimpleDateFormat("HH:mm:ss", Locale.ROOT);
  }
  
  public void log(String tag, String message) {
    mLogMessages.add(new LogMessage(new Date(), tag, message));
    notifyDataSetChanged();
  }
  
  public void clear() {
    mLogMessages.clear();
    notifyDataSetChanged();
  }
  
  @Override
  public int getCount() {
    return mLogMessages.size();
  }

  @Override
  public Object getItem(int position) {
    return mLogMessages.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    final LogMessage msg = mLogMessages.get(position);
    LogMessageHolder holder;
    if (convertView == null) {
      View view = mLayoutInflater.inflate(R.layout.log_item, null);
      holder = new LogMessageHolder(view, (TextView) view.findViewById(R.id.text_date),
          (TextView) view.findViewById(R.id.text_content));
      view.setTag(holder);
      convertView = view;
    } else {
      holder = (LogMessageHolder) convertView.getTag();
    }
    holder.textDate.setText(mDateFormat.format(msg.date));
    holder.textContent.setText(String.format("%s: %s", msg.tag, msg.message));
    return convertView;
  }
}